package com.incar.chuxing.api;

import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.incar.chuxing.BuildConfig;
import com.incar.chuxing.application.MyApplication;
import com.incar.chuxing.utils.Logger;
import com.incar.chuxing.utils.SPUtils;
import com.incar.chuxing.utils.ThreadPool;

import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.incar.chuxing.api.UrlContainer.Request.BASE_URL_PARSE;
import static com.incar.chuxing.api.UrlContainer.Request.BASE_URL_PARSE_TEST;


public class ParseApiStore {
    private static ParseApiStore instance = null;
    private static Retrofit retrofit;

    private ParseApiStore() {
    }

    public static ParseApiStore getInstance() {
        if (instance == null) {
            synchronized (ParseApiStore.class) {
                if (instance == null) {
                    instance = new ParseApiStore();
                }
            }
        }
        return instance;
    }

    public ParseApiService getTinyApiService() {
        String baseUrl;
        if (!BuildConfig.DEBUG) {
            baseUrl = BASE_URL_PARSE;
        } else if (3 == SPUtils.getInstance(MyApplication.getInstance().getApplicationContext()).getIntValue("$s_urlMode")) {
            baseUrl = BASE_URL_PARSE;
        } else {
            baseUrl = BASE_URL_PARSE_TEST;
        }
        return getRetrofit(baseUrl).create(ParseApiService.class);
    }

    public Retrofit getRetrofit(String baseUrl) {
        //配置okHttp
        OkHttpClient.Builder builder = new OkHttpClient
                .Builder()
                .readTimeout(120, TimeUnit.SECONDS);
        builder.addInterceptor(chain -> {
            Request original = chain.request();
            Request request = original.newBuilder()
                    .header("X-Parse-Application-Id", "e8b9ed3e57a3c04c56b4ec7bd82d3b47")
                    .header("X-Parse-REST-API-Key", "4c56b4ec7bd82d3b47e8b9ed3e57a3c0")
                    .header("Content-Type", "application/json")
                    .build();
            return chain.proceed(request);
        });
        if (BuildConfig.DEBUG) {
            //debug模式
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Logger.i("OkHttpClient", "OkHttpMessageParse:" + message);
                }
            });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(logging);
            builder.addInterceptor(MyApplication.chuckInterceptor);
        }
        //配置Retrofit
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create(getGson()))
                .build();

        return retrofit;
    }

    /**
     * java bean 转化json数据  序列化
     * 解析反序列化
     *
     * @return
     */
    public Gson getGson() {
        return new GsonBuilder()
                .serializeNulls()//允许序列化反序列化为null
                .create();
    }

    /*parse的基本参数*/
    private Map<String, String> getParseBaseParameterReq(String serialNumber, String opOrder, String carBoxType, String opUid, String orderid, String carBlename) {
        String time = new Date().getTime() + "";
        HashMap hashMap = new HashMap();
        hashMap.put("platforms", "android");
        hashMap.put("logType", "req");
        hashMap.put("time", time + "");
        hashMap.put("prjectName", "incar");
        hashMap.put("serialNumber", serialNumber);
        hashMap.put("description", "");
        hashMap.put("opOrder", opOrder + "");
        hashMap.put("carBoxType", carBoxType + "");
        hashMap.put("opUid", opUid + "");
        hashMap.put("orderid", orderid + "");
        if (!carBoxType.equals("zhixintong")) {
            hashMap.put("mac", carBlename + "");
        } else {
            hashMap.put("idc", carBlename + "");
        }

        return hashMap;
    }

    /*parse的基本参数*/
    private Map<String, String> getParseBaseParameterRes(String serialNumber, String opOrder, String opResult, String errDes, String opResultDada, String carBoxType, String opUid, String orderid, String carBlename) {
        String time = new Date().getTime() + "";
        HashMap hashMap = new HashMap();
        hashMap.put("platforms", "android");
        hashMap.put("logType", "res");
        hashMap.put("time", time + "");
        hashMap.put("prjectName", "incar");
        hashMap.put("serialNumber", serialNumber);
        hashMap.put("description", "");
        hashMap.put("opOrder", opOrder + "");
        hashMap.put("carBoxType", carBoxType + "");
        hashMap.put("opUid", opUid + "");
        hashMap.put("orderid", orderid + "");
        if (!carBoxType.equals("zhixintong")) {
            hashMap.put("mac", carBlename + "");
        } else {
            hashMap.put("idc", carBlename + "");
        }
        hashMap.put("opResult", opResult + "");
        hashMap.put("errDes", errDes + "");
        hashMap.put("opResultDada", opResultDada + "");
        return hashMap;
    }

    public void commitBleReqLog(String serialNumber, String opOrder, String carBoxType, String opUid, String orderid, String carBlename) {
        ThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                /*parse*/
                Map<String, String> parseMapOne = getParseBaseParameterReq(serialNumber, opOrder, carBoxType, opUid, orderid, carBlename);
                try {
                    getTinyApiService().parseBleLog(parseMapOne).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void commitBleResLog(String serialNumber, String opOrder, String opResult, String errDes, String opResultDada, String carBoxType, String opUid, String orderid, String carBlename) {
        ThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                /*parse*/
                Map<String, String> parseMapOne = getParseBaseParameterRes(serialNumber, opOrder, opResult, errDes, opResultDada, carBoxType, opUid, orderid, carBlename);
                try {
                    getTinyApiService().parseBleLog(parseMapOne).execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /*parseLaunchLog的基本参数*/
    private Map<String, Object> getLaunchParams(int isHaveorder, double carLatitude, double carLongitude, String carId) {
        HashMap hashMap = new HashMap();
        hashMap.put("phoneSysVersion", android.os.Build.VERSION.RELEASE + "");
        hashMap.put("appVersion", ((MyApplication) MyApplication.getInstance()).getAppVersion() + "");
        hashMap.put("device_brand", android.os.Build.BRAND + android.os.Build.MODEL + "");
        hashMap.put("uid", MyApplication.getInstance().getUid() + "");
        hashMap.put("platform", "1");
        hashMap.put("phoneModel", android.os.Build.BRAND + android.os.Build.MODEL + "");
        hashMap.put("timestamp", new Date().getTime() + "");
        hashMap.put("adCode", MyApplication.getInstance().getAdCode() + "");
        hashMap.put("areaCode", MyApplication.getInstance().getAreaCode() + "");
        hashMap.put("latitude", MyApplication.getInstance().getCurPosition()[0]);
        hashMap.put("longitude", MyApplication.getInstance().getCurPosition()[1]);
        hashMap.put("isHaveorder", isHaveorder == 1);
        hashMap.put("carLatitude", carLatitude == 0 ? null : carLatitude);
        hashMap.put("carLongitude", carLongitude == 0 ? null : carLongitude);
        hashMap.put("carId", carId != null ? Long.parseLong(carId) : null);
        return hashMap;
    }

    /*提交parseLaunchLog*/
    public void commitLaunchLog(int isHaveorder, double carLatitude, double carLongitude, String carId) {
        ThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                /*parse*/
                try {
                    Map<String, Object> parseMapOne = getLaunchParams(isHaveorder, carLatitude, carLongitude, carId);
                    Type typeParseMapOne = new TypeToken<Map<String, String>>() {
                    }.getType();
                    JSONObject bodyJson = new JSONObject(new Gson().toJson(parseMapOne, typeParseMapOne));
                    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
                    getTinyApiService().parseLaunchLog(body).execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /*parseLaunchLog的基本参数*/
    private Map<String, Object> getOilLowParams(String carId, String orderId, LatLng curLatLng, LatLng carLatLng, String remainingMileage,
                                                String distanceBetweenPAndG, String results, String CurrOilMileageThreshold, String CurrBackOilCarDistanceLimit) {
        HashMap hashMap = new HashMap();
        hashMap.put("userId", MyApplication.getInstance().getUid() + "");
        hashMap.put("time", new Date().getTime() + "");
        hashMap.put("peopleLatitude", curLatLng.latitude);
        hashMap.put("peopleLongitude", curLatLng.longitude);
        hashMap.put("gasolineStationLatitude", carLatLng.latitude);
        hashMap.put("gasolineStationLongitude", carLatLng.longitude);
        hashMap.put("distanceBetweenPAndG", distanceBetweenPAndG);
        hashMap.put("remainingMileage", remainingMileage);
        hashMap.put("results", results);
        hashMap.put("CurrOilMileageThreshold", CurrOilMileageThreshold);
        hashMap.put("CurrBackOilCarDistanceLimit", CurrBackOilCarDistanceLimit);
        hashMap.put("carId", carId);
        hashMap.put("orderId", orderId);
        return hashMap;
    }


    /*提交commitOilLowLog*/
    public void commitOilLowLog(String carId, String orderId, LatLng curLatLng, LatLng carLatLng, String remainingMileage,
                                String distanceBetweenPAndG, String results, String CurrOilMileageThreshold, String CurrBackOilCarDistanceLimit) {
        ThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                /*parse*/
                try {
                    Map<String, Object> parseMapOne = getOilLowParams(carId, orderId, curLatLng, carLatLng,
                            remainingMileage, distanceBetweenPAndG, results, CurrOilMileageThreshold, CurrBackOilCarDistanceLimit);
                    Type typeParseMapOne = new TypeToken<Map<String, String>>() {
                    }.getType();
                    JSONObject bodyJson = new JSONObject(new Gson().toJson(parseMapOne, typeParseMapOne));
                    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
                    getTinyApiService().commitOilLowLog(body).execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    /*parseLaunchLog的基本参数*/
    private Map<String, Object> getClickReturnCarParams(String carId, String orderId) {
        HashMap hashMap = new HashMap();
        hashMap.putAll(MyApplication.getInstance().getRequestFieldMap());
        hashMap.put("time", new Date().getTime() + "");
        hashMap.put("carId", carId);
        hashMap.put("orderId", orderId);
        return hashMap;
    }


    /*提交commitOilLowLog*/
    public void commitClickReturnCarLog(String carId, String orderId) {
        ThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                /*parse*/
                try {
                    Map<String, Object> parseMapOne = getClickReturnCarParams(carId, orderId);
                    Type typeParseMapOne = new TypeToken<Map<String, String>>() {
                    }.getType();
                    JSONObject bodyJson = new JSONObject(new Gson().toJson(parseMapOne, typeParseMapOne));
                    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyJson.toString());
                    getTinyApiService().commitClickReturnCarLog(body).execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


}
